package shuimin.weixin.security;

import pond.common.HTTP;
import pond.common.S;
import pond.common.struc.Cache;
import pond.web.EndToEndException;
import shuimin.weixin.Constant;

import java.io.IOException;
import java.util.Map;

/**
 * Created by sky on 16/5/18.
 */
public class JsApiTicket {

    private static final Cache<String, Object> JS_API_TICKET_POOL = Cache.lruCache(1000);

    public static String getTicket() {
        Object _expires_time = JS_API_TICKET_POOL.get("expires_time");
        if (_expires_time != null) {
            Long expires_time = (Long) _expires_time;
            if (expires_time < S.now()) {
                _getTicket();
            }
        } else _getTicket();

        return (String) JS_API_TICKET_POOL.get("ticket");

    }

    private static void _getTicket() {
        try {
            String url = Constant.QY_API_URL_PREFIX + Constant.JS_API_TICKET_URL + "access_token=" + AccessToken.getAccessToken();
            HTTP.get(url, resp -> {

                Map<String, Object> map = shuimin.weixin.HTTP.parseRespToJson(resp);

                if (map == null) {
                    throw new RuntimeException("微信通讯失败");
                }
                Object errcode = map.get("errcode");
                if (!errcode .equals(0)) {
                    throw new EndToEndException(500, (String) map.get("errmsg"));
                }
                JS_API_TICKET_POOL.put("ticket", map.get("ticket"));
                Integer expires_in = (Integer) map.get("expires_in");

                JS_API_TICKET_POOL.put("expires_time", expires_in * 1000 + S.now() - 1000);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
